package com.jlu.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

@RestController
public class UserController {

//  服务注册与发现客户端对象
  @Resource
  private DiscoveryClient discoveryClient;

//  使用LoadBalanceClient负载均衡
  @Resource
  private LoadBalancerClient loadBalancerClient;

  @Resource
  private RestTemplate restTemplate;

  private static final Logger log = LoggerFactory.getLogger(UserController.class);

  @GetMapping("user")
  public String invokedemo(){
//    log.info("user is ok");

//    RestTemplate restTemplate = new RestTemplate();
//    String order = restTemplate.getForObject("http://"+ rondom() +"/order", String.class);


//    使用ribbon+restTemplate实现负载均衡
// 1.DiscoverClient

//    List<ServiceInstance> orders = discoveryClient.getInstances("ORDERS");
//    for (ServiceInstance order : orders) {
//      log.info("服务主机: {} 服务端口: {} 服务地址: {}",order.getHost(),order.getPort(),order.getUri());
//    }
//    String result = new RestTemplate().getForObject(orders.get(0).getUri() + "/order", String.class);

//    2.LoadBalancerClient 3.@LoadBalance
        ServiceInstance serviceInstance = loadBalancerClient.choose("ORDERS");
//        log.info("服务主机: {} 服务端口: {} 服务地址: {}",serviceInstance.getHost(),serviceInstance.getPort(),serviceInstance.getUri());
//        String result = restTemplate.getForObject(serviceInstance.getUri() + "/order", String.class);

//    3.使用@LoadBalance注解，使对象具有负载均衡特性
    String result = restTemplate.getForObject("http://ORDERS/order", String.class);
//    log.info(order);
//    return "调用服务成功"+order;
    return "ok" + result;
  }

//  自定义随即策略
  public String rondom(){

    ArrayList<String> hosts = new ArrayList<String>();
    hosts.add("localhost:9999");
    hosts.add("localhost:9990");
    int i = new Random().nextInt(hosts.size());
    return hosts.get(i);
  }
}
